﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Configuration;
using System.Transactions;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Facebook;
using Microsoft.Web.WebPages.OAuth;
using SimpleScrum.Areas.Admin.Models;
using SimpleScrum.Areas.Scrum.Models;
using SimpleScrum.Core.Entities;
using SimpleScrum.Filters;
using SimpleScrum.Helpers;
using SimpleScrum.Models;
using WebMatrix.WebData;
using UserProfile = SimpleScrum.Models.UserProfile;

namespace SimpleScrum.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class AccountController : Controller
    {
        public UsersModel ObjUsers;

        public string email = "", firstname = "", lastname = "";

        public AccountController()
        {
            ObjUsers = new UsersModel();
        }

        //
        // GET: /Account/Login

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        //
        // POST: /Account/Login

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid && WebSecurity.Login(model.Email, model.Password, persistCookie: model.RememberMe))
            {
                if (Roles.IsUserInRole(model.Email, "user"))
                {
                    return RedirectToAction("Index", "DashBoard", new {area = "Scrum"});
                }
                else if (Roles.IsUserInRole(model.Email, "admin"))
                {
                    return RedirectToAction("Index", "ControlPanel", new {area = "Admin"});
                }
                else
                {
                    return RedirectToLocal(returnUrl);
                }
            }
            //Response.SetStatus(HttpStatusCode.Forbidden);
            ////.........................simple from database.....................
            //UserProfile users = AccountModel.GetUserProfileIdByEmail(model.Email).FirstOrDefault();
            //if (users != null)
            //{
            //    if (users.Password == model.Password)
            //    {
            //        FormsAuthentication.SetAuthCookie(model.Email, createPersistentCookie: true);
            //        return RedirectToAction("Index", "Home");
            //    }
            //    else
            //    {
            //        return RedirectToLocal(returnUrl);
            //    }
            //}
            //else
            //{
            //    return RedirectToLocal(returnUrl);
            //}
            ////.......................End simple from database.....................
            /// 
            //If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "The email or password provided is incorrect.");
            return View(model);
        }

        //
        // POST: /Account/LogOff

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            if (HttpContext.Session != null) HttpContext.Session.Abandon();
            WebSecurity.Logout();
            Session.Remove("facebooktoken");

            return RedirectToRoute("Default", new {action = "Index", controller = "Home"});
        }

        //
        // GET: /Account/Register

        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    //.......testing code by sending email confirmation 2 step.......
                    //// WebSecurity.InitializeDatabaseConnection("SimpleScrumDatabaseConnection", "UserProfile", "UserId", "Email", "Password", true);
                    // string confirmationToken = WebSecurity.CreateUserAndAccount(model.Email, model.Password, new { model.Email }, true);
                    //dynamic email = new Email("RegEmail");
                    // email.To = model.Email;
                    // email.UserName = model.Email;
                    // email.ConfirmationToken = confirmationToken;
                    // email.Send();
                    // return RedirectToAction("RegisterStepTwo", "Account");
                    //.......End testing code by sending email confirmation 2 step.......
                    //MembershipCreateStatus createStatus;
                    //Membership.CreateUser(
                    //    model.Email,
                    //    model.Password,
                    //    model.Email,
                    //    passwordQuestion: null,
                    //    passwordAnswer: null,
                    //    isApproved: true,
                    //    providerUserKey: null,
                    //    status: out createStatus);
                    NHibernateHelper.DatabaseInitialize();
                    var newUsers = new Users();
                    newUsers.Email = model.Email;
                    newUsers.FirstName = model.FirstName;
                    newUsers.LastName = model.LastName;
                    newUsers.Gender = model.Gender;
                    newUsers.JoinDate = DateTime.Now;
                    newUsers.LastLogin = DateTime.Now;
                    newUsers.Status = 0;
                    newUsers.Type = 0;
                    ObjUsers.NewUsers(newUsers);
                    WebSecurity.CreateUserAndAccount(model.Email, model.Password);
                    if (Roles.GetAllRoles() == null)
                    {
                        Roles.CreateRole("admin");
                        Roles.CreateRole("user");
                    }
                    Roles.AddUserToRole(model.Email, model.Email == "scrumsimple@gmail.com" ? "admin" : "user");
                    WebSecurity.Login(model.Email, model.Password);
                    return RedirectToAction("Index", "DashBoard", new {area = "Scrum"});
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // POST: /Account/ChangeInformation


        public ActionResult ChangeInformation()
        {
            Users userCurrent = ObjUsers.GetUsersById(ObjUsers.GetUsersIdByEmail());
            return View(userCurrent);
        }

        //
        // POST: /Account/ChangeInformation

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ChangeInformation(Guid id, Users usersCurrent)
        {
            id = ObjUsers.GetUsersIdByEmail();
            try
            {
                ObjUsers.UpdateUsers(usersCurrent);
                return RedirectToAction("Manage", "Account");
            }
            catch
            {
                return View();
            }
        }

        //
        // POST: /Account/Disassociate

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Disassociate(string provider, string providerUserId)
        {
            string ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);
            ManageMessageId? message = null;

            // Only disassociate the account if the currently logged in user is the owner
            if (ownerAccount == User.Identity.Name)
            {
                // Use a transaction to prevent the user from deleting their last login credential
                using (
                    var scope = new TransactionScope(TransactionScopeOption.Required,
                                                     new TransactionOptions
                                                         {
                                                             IsolationLevel = IsolationLevel.Serializable
                                                         }))
                {
                    bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
                    if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1)
                    {
                        OAuthWebSecurity.DeleteAccount(provider, providerUserId);
                        scope.Complete();
                        message = ManageMessageId.RemoveLoginSuccess;
                    }
                }
            }

            return RedirectToAction("Manage", new {Message = message});
        }

        //
        // GET: /Account/Manage

        public ActionResult Manage(ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess
                    ? "Your password has been changed."
                    : message == ManageMessageId.SetPasswordSuccess
                          ? "Your password has been set."
                          : message == ManageMessageId.RemoveLoginSuccess
                                ? "The external login was removed."
                                : "";
            ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.ReturnUrl = Url.Action("Manage");
            return View();
        }

        //
        // POST: /Account/Manage

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Manage(LocalPasswordModel model)
        {
            bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.HasLocalPassword = hasLocalAccount;
            ViewBag.ReturnUrl = Url.Action("Manage");
            if (hasLocalAccount)
            {
                if (ModelState.IsValid)
                {
                    // ChangePassword will throw an exception rather than return false in certain failure scenarios.
                    bool changePasswordSucceeded;
                    try
                    {
                        changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword,
                                                                             model.NewPassword);
                    }
                    catch (Exception)
                    {
                        changePasswordSucceeded = false;
                    }

                    if (changePasswordSucceeded)
                    {
                        return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
                    }
                    else
                    {
                        ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                    }
                }
            }
            else
            {
                // User does not have a local password so remove any validation errors caused by a missing
                // OldPassword field
                ModelState state = ModelState["OldPassword"];
                if (state != null)
                {
                    state.Errors.Clear();
                }

                if (ModelState.IsValid)
                {
                    try
                    {
                        WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword);
                        return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
                    }
                    catch (Exception e)
                    {
                        ModelState.AddModelError("", e);
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // POST: /Account/ExternalLogin

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLogin(string provider, string returnUrl)
        {
            return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new {ReturnUrl = returnUrl}));
        }


        //GET: /Account/ExternalLoginCallback

        [AllowAnonymous]
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            AuthenticationResult result =
                OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new {ReturnUrl = returnUrl}));
            if (!result.IsSuccessful)
            {
                return RedirectToAction("ExternalLoginFailure");
            }

            //Save the accesstoken into session
            //Session["accesstoken"] = result.ExtraData["accesstoken"];
            //Session["id"] = result.ExtraData["id"];
            if (result.ExtraData.Keys.Contains("accesstoken"))
            {
                Session["facebooktoken"] = result.ExtraData["accesstoken"];
            }

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                if (Roles.IsUserInRole(result.UserName, "user"))
                {
                    return RedirectToAction("Index", "DashBoard", new {area = "Scrum"});
                }
                else if (Roles.IsUserInRole(result.UserName, "admin"))
                {
                    return RedirectToAction("Index", "ControlPanel", new {area = "Admin"});
                }
                else
                {
                    return RedirectToLocal(returnUrl);
                }
            }

            if (User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
                if (Roles.IsUserInRole(result.UserName, "user"))
                {
                    return RedirectToAction("Index", "DashBoard", new {area = "Scrum"});
                }
                else if (Roles.IsUserInRole(result.UserName, "admin"))
                {
                    return RedirectToAction("Index", "ControlPanel", new {area = "Admin"});
                }
                else
                {
                    return RedirectToLocal(returnUrl);
                }
            }
            else
            {
                // User is new, ask for their desired membership name
                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                ViewBag.ReturnUrl = returnUrl;
                if (result.ExtraData.ContainsKey("email"))
                    email = result.ExtraData["email"];
                if (result.ExtraData.ContainsKey("firstname"))
                    firstname = result.ExtraData["firstname"];
                if (result.ExtraData.ContainsKey("lastname"))
                    lastname = result.ExtraData["lastname"];
                if (result.ExtraData.ContainsKey("name"))
                {
                    string name = result.ExtraData["name"];
                    string[] names = name.Split(' ');
                    if (names.Length == 1)
                        lastname = name;
                    if (names.Length > 1)
                    {
                        firstname = names[0];
                        lastname = string.Join(" ", names.Skip(1).ToList());
                    }
                }
                if (result.Provider == "facebook")
                {
                    return View("ExternalLoginConfirmation",
                                new RegisterExternalLoginModel
                                    {
                                        Email = result.UserName,
                                        ExternalLoginData = loginData,
                                        FirstName = firstname,
                                        LastName = lastname,
                                    });
                }
                if (result.Provider == "yahoo")
                {
                    if (result.ExtraData.ContainsKey("fullName"))
                    {
                        string name = result.ExtraData["fullName"];
                        string[] names = name.Split(' ');
                        if (names.Length == 1)
                            lastname = name;
                        if (names.Length > 1)
                        {
                            firstname = names[0];
                            lastname = string.Join(" ", names.Skip(1).ToList());
                        }
                    }
                    return View("ExternalLoginConfirmation",
                                new RegisterExternalLoginModel
                                    {
                                        Email = result.UserName,
                                        ExternalLoginData = loginData,
                                        FirstName = firstname,
                                        LastName = lastname,
                                    });
                }
                if (result.Provider == "linkedIn")
                {
                    if (result.ExtraData.ContainsKey("name"))
                    {
                        string name = result.ExtraData["name"];
                        string[] names = name.Split(' ');
                        if (names.Length == 1)
                            lastname = name;
                        if (names.Length > 1)
                        {
                            firstname = names[0];
                            lastname = string.Join(" ", names.Skip(1).ToList());
                        }
                    }
                    return View("ExternalLoginConfirmation",
                                new RegisterExternalLoginModel
                                    {
                                        Email = result.UserName,
                                        ExternalLoginData = loginData,
                                        FirstName = firstname,
                                        LastName = lastname,
                                    });
                }

                return View("ExternalLoginConfirmation",
                            new RegisterExternalLoginModel
                                {
                                    Email = result.UserName,
                                    ExternalLoginData = loginData,
                                    //FirstName = firstname,
                                    //LastName = lastname,
                                    //Gender = result.ExtraData["gender"],
                                    //Link = result.ExtraData["link"],
                                });
            }
        }

        //
        // POST: /Account/ExternalLoginConfirmation
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated ||
                !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (var db = new UsersContext())
                {
                    UserProfile newUser = db.UserProfiles.FirstOrDefault(u => u.Email.ToLower() == model.Email.ToLower());
                    //Check if user already exists
                    if (newUser == null)
                    {
                        // Insert name into the profile table
                        db.UserProfiles.Add(new UserProfile {Email = model.Email});
                        db.SaveChanges();
                        //Retrieve user information that requires the access token BY Install NuGet package for Facebook API
                        bool facebookVerified;

                        var client = new FacebookClient(Session["facebooktoken"].ToString());
                        dynamic response = client.Get("me", new {fields = "verified"});
                        if (response.ContainsKey("verified"))
                        {
                            facebookVerified = response["verified"];
                        }
                        else
                        {
                            facebookVerified = false;
                        }
                        //External User Information table insert db changes
                        //db.ExternalUsers.Add(new ExternalUserInformation
                        //{
                        //    UserId = newUser.UserId,
                        //    FirstName = model.FirstName,
                        //    LastName = model.LastName,
                        //    Gender = model.Gender,
                        //    Link = model.Link
                        //});
                        NHibernateHelper.DatabaseInitialize();
                        //Users table insert db changes
                        var newUsers = new Users();
                        newUsers.Id = Guid.NewGuid();
                        newUsers.Email = model.Email;
                        newUsers.FirstName = model.FirstName;
                        newUsers.LastName = model.LastName;
                        newUsers.Gender = model.Gender;
                        newUsers.JoinDate = DateTime.Now;
                        newUsers.LastLogin = DateTime.Now;
                        newUsers.Status = 0;
                        newUsers.Type = 0;
                        ObjUsers.NewUsers(newUsers);
                        db.SaveChanges();
                        if (Roles.GetAllRoles() == null)
                        {
                            Roles.CreateRole("admin");
                            Roles.CreateRole("user");
                        }
                        Roles.AddUserToRole(model.Email, model.Email == "scrumsimple@gmail.com" ? "admin" : "user");
                        //OAuth create profile and login
                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.Email);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);
                        return RedirectToAction("Index", "DashBoard", new {area = "Scrum"});
                    }
                    else
                    {
                        ModelState.AddModelError("Email",
                                                 "Email already exists. Please enter a different Email.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }

        //
        // GET: /Account/ExternalLoginFailure

        [AllowAnonymous]
        public ActionResult ExternalLoginFailure()
        {
            return View();
        }

        [AllowAnonymous]
        [ChildActionOnly]
        public ActionResult ExternalLoginsList(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return PartialView("_ExternalLoginsListPartial", OAuthWebSecurity.RegisteredClientData);
        }

        [ChildActionOnly]
        public ActionResult RemoveExternalLogins()
        {
            ICollection<OAuthAccount> accounts = OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name);
            var externalLogins = new List<ExternalLogin>();
            foreach (OAuthAccount account in accounts)
            {
                AuthenticationClientData clientData = OAuthWebSecurity.GetOAuthClientData(account.Provider);

                externalLogins.Add(new ExternalLogin
                    {
                        Provider = account.Provider,
                        ProviderDisplayName = clientData.DisplayName,
                        ProviderUserId = account.ProviderUserId,
                    });
            }

            ViewBag.ShowRemoveButton = externalLogins.Count > 1 ||
                                       OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            return PartialView("_RemoveExternalLoginsPartial", externalLogins);
        }

        #region Forgot Password Methods

        /// <summary>
        ///     This allows the non-logged on user to have his password
        ///     reset and emailed to him.
        /// </summary>
        /// <returns></returns>
        public ActionResult ForgotPassword()
        {
            var viewModel = new ForgotPasswordViewModel
                {
                    RequireSecretQuestionAndAnswer = Membership.RequiresQuestionAndAnswer
                };
            return View(viewModel);
        }

        /// <summary>
        ///     This is the GET action to collect the answer and then continue.
        ///     This is only hit if the web.config/system.web/membership provider is
        ///     set with the attribute requiresQuestionAndAnswer="true".
        /// </summary>
        /// <param name="model">ForgotPasswordViewModel</param>
        /// <returns></returns>
        public virtual ActionResult EnterSecretAnswer(ForgotPasswordViewModel model)
        {
            return View(model);
        }

        /// <summary>
        ///     Reset the password for the user and email it to him.
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public virtual ActionResult ForgotPassword(ForgotPasswordViewModel model)
        {
            string userName = Membership.GetUserNameByEmail(model.Email);
            // Get the userName by the email address
            if (string.IsNullOrEmpty(userName))
            {
                ModelState.AddModelError("Email",
                                         "Email address does not exist. Please check your spelling and try again.");
                return RedirectToAction("ForgotPassword");
            }

            MembershipUser user = Membership.GetUser(userName);
            if (user == null)
            {
                ModelState.AddModelError("", "The user does not exist.  Please check your entry and try again.");
                return RedirectToAction("ForgotPassword");
            }

            if (model.RequireSecretQuestionAndAnswer && model.Checked == false)
            {
                // Get the SecretQuestion
                model.SecretQuestion = user.PasswordQuestion;
                model.Checked = true;

                return RedirectToAction("EnterSecretAnswer", model);
            }

            if (model.RequireSecretQuestionAndAnswer && model.Checked)
            {
                if (string.IsNullOrEmpty(model.SecretAnswer))
                {
                    ModelState.AddModelError("SecretAnswer", "The Secret Answer is required.");
                    return RedirectToAction("EnterSecretAnswer", model);
                }
            }


            // Now reset the password
            string newPassword = string.Empty;

            if (Membership.RequiresQuestionAndAnswer)
            {
                try
                {
                    newPassword = user.ResetPassword(model.SecretAnswer);
                }
                catch (NullReferenceException)
                {
                    ModelState.AddModelError("PasswordAnswer", "The Secret Password is required.");
                    return RedirectToAction("EnterSecretAnswer", model);
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("PasswordAnswer", ex.Message);
                    return RedirectToAction("EnterSecretAnswer", model);
                }
            }
            else
            {
                newPassword = user.ResetPassword();
            }

            // Email the new pasword to the user
            try
            {
                var smtp = (SmtpSection) ConfigurationManager.GetSection("system.net/mailSettings/smtp");

                // Set the MailerModel properties that will be passed to the MvcMailer object.
                // Feel free to modify the properties as you need.
                var m = new MailerModel();
                m.Email = user.Email;
                m.Password = newPassword;
                m.FromEmail = smtp.From;
                m.Subject = "Password Reset From Simple Scrum";
                m.ToEmail = model.Email;

                //WebSecurity.ResetPassword(m).Send();
            }
            catch (Exception)
            {
            }

            return RedirectToAction("ForgotPasswordSuccess");
        }


        public ActionResult ForgotPasswordSuccess()
        {
            return View();
        }

        #endregion

        #region Helpers

        public enum ManageMessageId
        {
            ChangePasswordSuccess,
            SetPasswordSuccess,
            RemoveLoginSuccess,
        }

        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User already exists. Please enter a different email.";

                case MembershipCreateStatus.DuplicateEmail:
                    return
                        "A user for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return
                        "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return
                        "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return
                        "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }

        internal class ExternalLoginResult : ActionResult
        {
            public ExternalLoginResult(string provider, string returnUrl)
            {
                Provider = provider;
                ReturnUrl = returnUrl;
            }

            public string Provider { get; private set; }
            public string ReturnUrl { get; private set; }

            public override void ExecuteResult(ControllerContext context)
            {
                OAuthWebSecurity.RequestAuthentication(Provider, ReturnUrl);
            }
        }

        #endregion

        #region RegisterStepTwo by sending email

        [AllowAnonymous]
        public ActionResult RegisterStepTwo()
        {
            return View();
        }

        [AllowAnonymous]
        public ActionResult RegisterConfirmation(string id)
        {
            if (WebSecurity.ConfirmAccount(id))
            {
                return RedirectToAction("ConfirmationSuccess");
            }
            return RedirectToAction("ConfirmationFailure");
        }

        [AllowAnonymous]
        public ActionResult ConfirmationSuccess()
        {
            return View();
        }

        [AllowAnonymous]
        public ActionResult ConfirmationFailure()
        {
            return View();
        }

        #endregion RegisterStepTwo by sending email

        //
        //forgot password

        //
        //
    }
}